package bb.lanxing.activity.sport;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.activity.base.BaseActivity;
import bb.lanxing.adapter.sport.SportRecordAdapter;
import bb.lanxing.model.database.Workout;
import bb.lanxing.network.BiCiCallback;
import bb.lanxing.network.MyHttpClient;
import bb.lanxing.view.BiciAlertDialogBuilder;
import okhttp3.Request;

public class SportRecordActivity extends BaseActivity {
    public static final String EXTRA_SHOW_MODE = "choose_mode";

    private Spinner spinner;
    private ArrayAdapter<String> mSpinnerAdapter;
    private final List<String> yearList = new ArrayList<>();

    private TabLayout tabLayout;
    private SportRecordAdapter adapter;
    private final List<String> monthList = new ArrayList<>();
    private final List<List<Workout>> workoutsList = new ArrayList<>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sport_record);

        ImageView back = findViewById(R.id.back);
        back.setOnClickListener(v -> onBackPressed());

        ImageView menu_history_fit = findViewById(R.id.menu_history_fit);
        menu_history_fit.setOnClickListener(v -> new BiciAlertDialogBuilder(this)
                .setTitle(R.string.workout_merge_tips_title).setMessage(R.string.workout_merge_tips_msg)
                .setPositiveButton(R.string.confirm, (dialog, which) ->
                        startActivity(new Intent(getApplicationContext(), HistoryListActivity.class)
                                .putExtra(EXTRA_SHOW_MODE, 2))).show());
        ImageView menu_history_sync = findViewById(R.id.menu_history_sync);
        menu_history_sync.setOnClickListener(v -> LocalWorkoutActivity.Companion.start(context));

        spinner = findViewById(R.id.spinner);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                loadData(Integer.parseInt(yearList.get(position)));
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        tabLayout = findViewById(R.id.tabLayout);
        tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        ViewPager viewPager = findViewById(R.id.pager);

        adapter = new SportRecordAdapter(getSupportFragmentManager());
        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);

        loadYearList();
    }

    private void loadYearList() {
        BiCiCallback biCiCallback = new BiCiCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                super.onFailure(request, e);
            }

            @Override
            public void onResponseString(@NonNull String string) {
                if (!TextUtils.isEmpty(string)) {
                    try {
                        JSONObject jsonObject = new JSONObject(string);
                        int code = jsonObject.optInt("code");
                        if (200 == code) {
                            try {
                                JSONArray jSONArray = new JSONObject(string).getJSONArray("rows");
                                yearList.clear();
                                for (int i = 0; i < jSONArray.length(); i++) {
                                    String year = jSONArray.getJSONObject(i).getString("year");
                                    yearList.add(year);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            getActivity().runOnUiThread(() -> {
                                mSpinnerAdapter = new ArrayAdapter<>(SportRecordActivity.this, android.R.layout.simple_spinner_item, yearList);
                                mSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                                spinner.setAdapter(mSpinnerAdapter);
                                spinner.setSelection(yearList.size() - 1);
                            });
                        }
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        };
        MyHttpClient.requestUserHistoryYears(biCiCallback, App.getContext().getUserId());
    }

    private void loadData(int year) {
        BiCiCallback biCiCallback = new BiCiCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                super.onFailure(request, e);
            }

            @Override
            public void onResponseString(@NonNull String string) {
                if (!TextUtils.isEmpty(string)) {
                    try {
                        JSONObject jsonObject = new JSONObject(string);
                        int code = jsonObject.optInt("code");
                        if (200 == code) {
                            try {
                                JSONArray jSONArray = new JSONObject(string).getJSONArray("rows");
                                monthList.clear();
                                workoutsList.clear();
                                int len = jSONArray.length();
                                for (int i = 0; i < len; i++) {
                                    String month = jSONArray.getJSONObject(i).getString("month");
                                    monthList.add(Integer.valueOf(month) + " " + getString(R.string.month));
                                    JSONArray itemDataSet = jSONArray.getJSONObject(i).getJSONArray("itemDataSet");
                                    int size = itemDataSet.length();
                                    List<Workout> workouts = new ArrayList<>();
                                    for (int j = 0; j < size; j++) {
                                        Workout workout = new Workout(itemDataSet.getJSONObject(j), true);
                                        if (Workout.getByServerId(workout.getServerId()) == null) {
                                            workout.setId(null);
                                            workout.save();
                                        }
                                        workouts.add(workout);
                                    }
                                    workoutsList.add(workouts);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            getActivity().runOnUiThread(() -> {
                                adapter.updateData(monthList, workoutsList);
                                tabLayout.getTabAt(workoutsList.size() - 1).select();
                            });
                        }
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        };
        MyHttpClient.getAllWorkouts(biCiCallback, year, App.getContext().getUserId());
    }
}